import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  if (store.getters.token) {
    if (to.path === '/login') {
      NProgress.done()
      next('/')
    } else {
      // 获取用户信息的前提 1.有token 2.去的不是登录页
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // console.log('个人信息', roles.menus)
        console.log('个人信息', roles)
        // console.log('动态路由的数组', asyncRoutes)
        // 1.遍历动态路由
        // 2.结合个人信息 -> 依次匹配动态的路由名称name
        // 3.一旦匹配成功，添加到路由表
        const filterRoutes = asyncRoutes.filter(item => {
          // console.log(item.name)
          return roles.menus.includes(item.name)
        })
        // console.log(filterRoutes)
        // 修复两个问题
        // 1.访问路径404 -> 需要把它放到最后面
        router.addRoutes([...filterRoutes], { path: '*', redirect: '/404', hidden: true })
        store.commit('user/setRoutes', filterRoutes)
        // 2.刷新白屏 需要再次转发
        next(to.path)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      NProgress.done()
      next('/login')
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})
